

import { baseURL } from "./base";
let config = {
  // 上传图片的API
  upload_img_url: `${baseURL}/app-api/infra/file/upload`,
  token:uni.getStorageSync("token")
};
class Uploader {
  constructor() {}
  choose(num) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: num,
        sourceType: ["camera","album"],
        success(res) {
          resolve(res.tempFilePaths);
        },
        fail(err) {
          console.log(err);
          reject(err);
        },
      });
    });
  }
  upload_one(path) {
    return new Promise((resolve, reject) => {
      uni.showLoading({
        title: "上传中",
      });
      uni.uploadFile({
        url: config.upload_img_url,
        filePath: path,
        name: 'file',
        header: {
        	"authorization": "Bearer " + uni.getStorageSync("token"),
        	"tenant-id":"1",
        	// "Content-Type": "application/json;charset=UTF-8"
        },
        success: (uploadFileRes) => {
			console.log(uploadFileRes.data,"uploadFileRes.data.data")
          if ("string" === typeof uploadFileRes.data) {
            resolve(JSON.parse(uploadFileRes.data).data);
          } else {
            resolve(uploadFileRes.data.data);
          }
        },
        complete() {
          uni.hideLoading();
        },
      });
    });
  }
  upload(path_arr) {
    let num = path_arr.length;
    return new Promise(async (resolve, reject) => {
      let img_urls = [];
      for (let i = 0; i < num; i++) {
        let img_url = await this.upload_one(path_arr[i]);
        img_urls.push(img_url);
      }
      resolve(img_urls);
    });
  }
  choose_and_upload(num) {
    return new Promise(async (resolve, reject) => {
      let path_arr = await this.choose(num);
      let img_urls = await this.upload(path_arr);
      let obj = {path_arr,img_urls};
      resolve(obj);
    });
  }
}

let pro = new Uploader();

export default pro;
